<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Setting Index</title>
    <meta name="Setting Index" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="/node_modules/layui/dist/css/layui.css" rel="stylesheet">
</head>
<body>
<!--
本「综合演示」包含：自定义头部工具栏、获取表格数据、表格重载、自定义模板、单双行显示、单元格编辑、自定义底部分页栏、表格相关事件与操作、与其他组件的结合等相对常用的功能，以便快速掌握 table 组件的使用。
-->
<div style="padding: 16px;">
    <table class="layui-hide" id="test" lay-filter="test"></table>
</div>
<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <div class="layui-btn-container">
            <button id="selectAllBtn" class="layui-btn " lay-event="selectAll">全选全部设备操作</button>
            <button id="selectBtn" class="layui-btn " lay-event="openSelectModal">选择设备操作</button>
            <button class="layui-btn " lay-event="scheduleUpload">设置所有设备上传定时</button>

            <div class="layui-col-md2 "   style="margin-right: 10px">
                <select id="statusSelect" name="platformName" lay-search="" lay-filter="statusSelect">
                    <option value="1">绑定账户</option>
                    <option value="0">未绑定账户</option>
                </select>
            </div>
        </div>

    </div>


</script>


<script type="text/html" id="barDemo">
    <div class="layui-clear-space">
        <a class="layui-btn layui-btn-xs" lay-event="report">错误报告</a>

    </div>
</script>
<script src="/node_modules/layui/dist/layui.js"></script>
<script th:inline="none">
    layui.use(['table', 'dropdown', 'form', 'layer', 'jquery'], function () {
        var table = layui.table;
        var form = layui.form;
        var $ = layui.jquery;
        var layer = layui.layer;
        var dropdown = layui.dropdown;
        var status = 1;

        /**
         * 选择框监听。查询设备数据
         */
        form.on('select(statusSelect)', function(data) {
            console.log('Selected value:', data.value);
            if(status === data.value){
                console.log("相同！不进行请求")
                return ;
            }
            table.reloadData('test', {
                where: {
                    status: data.value
                },
                method:'POST',
                page: {
                    curr: 1 // 重新从第一页开始
                },
                done: function(res, curr, count){
                    status = data.value;
                }
            });
            // 在此处添加其他逻辑以处理选项更改
        });


        // 创建渲染实例
        table.render({
            elem: '#test',
            url: '/api/search/devices', // 此处为静态模拟数据，实际使用时需换成真实接口
            page: true,
            limits: [20, 50, 100, 200],
            method: 'POST',
            toolbar: '#toolbarDemo',
            defaultToolbar: ['filter', 'exports', 'print', {
                title: '提示',
                layEvent: 'LAYTABLE_TIPS',
                icon: 'layui-icon-tips'
            }],
            height: 'full-35', // 最大高度减去其他容器已占有的高度差
            css: [ // 重设当前表格样式
                '.layui-table-tool-temp{padding-right: 145px;}'
            ].join(''),
            cellMinWidth: 80,
            cols: [[
                {type: 'checkbox', fixed: 'left'},
                {
                    fixed: 'left', width: '50', title: '序号', sort: true, templet: function (d) {
                        return d.LAY_INDEX + 1;
                    }
                },
                {field: 'id', title: 'id', hide: true},
                {field: 'name', width: '200', title: '源作者'},
                {field: 'deviceId', width: '200', title: '设备id'},
                {fixed: 'right', title: '操作', width: 100, minWidth: 125, toolbar: '#barDemo'}
            ]],
            done: function () {

            },
            error: function (res, msg) {
                console.log(res, msg)
            }
        });

        // 触发表格复选框选择
        table.on('tool(test)', function (obj) {
            var data = obj.data; // 获得当前行数据
            if (obj.event === 'report') {
                $.ajax({
                    url: '/videoLog/get/List/device',
                    type: 'POST',
                    data: {
                        deviceId: data.deviceId
                    },
                    success: function (res) {
                        if(res.code === 0){
                            layer.open({
                                type: 1,
                                title: '错误报告',
                                area: ['800px', '600px'],
                                content: `
                                    <div style="border: 1px solid #ddd; padding: 15px; background-color: #f9f9f9; border-radius: 8px; max-height: 500px; overflow-y: auto;">
                                        `+ res.data +`
                                    </div>
                                `
                                ,
                                success: function (layero, index) {
                                    // console.log(layero, index);
                                }
                            });
                        }else{
                            layer.confirm('获取失败！！', {btn:['关闭']});
                        }
                    },
                    error: function (res) {
                        console.log(res)
                        layer.confirm('错误报告失败', {btn:['关闭']});
                    }
                })
            }
        });

        // 触发表格单选框选择
        table.on('radio(test)', function (obj) {
            console.log(obj)
        });

        // 行单击事件
        table.on('row(test)', function (obj) {
            //console.log(obj);
            //layer.closeAll('tips');
        });
        // 行双击事件
        table.on('rowDouble(test)', function (obj) {
            console.log(obj);
        });
        // 单元格编辑事件
        table.on('edit(test)', function (obj) {
            var field = obj.field; // 得到字段
            var value = obj.value; // 得到修改后的值
            var data = obj.data; // 得到所在行所有键值
            // 值的校验
            if (field === 'email') {
                if (!/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(obj.value)) {
                    layer.tips('输入的邮箱格式不正确，请重新编辑', this, {tips: 1});
                    return obj.reedit(); // 重新编辑 -- v2.8.0 新增
                }
            }
            // 编辑后续操作，如提交更新请求，以完成真实的数据更新
            // …
            layer.msg('编辑成功', {icon: 1});

            // 其他更新操作
            var update = {};
            update[field] = value;
            obj.update(update);
        });

        // 监听工具栏事件
        table.on('toolbar(test)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id);
            var deviceIds = [];
            var excuteFlag = false;
            var data = checkStatus.data;
            // layer.alert(JSON.stringify(obj.data));
            console.log(JSON.stringify(checkStatus))
            if(status === "0"){
                layer.msg('请选择已绑定账户的设备进行操作！', {icon: 2});
                return;
            }

            switch (obj.event) {
                case 'selectAll': {
                    deviceIds = ["all"];
                    excuteFlag = true;
                    break;
                }
                case 'openSelectModal': {
                    if (checkStatus.data.length === 0) {
                        layer.msg('请选择设备进行操作！', {icon: 2});
                        return;
                    }
                    deviceIds = checkStatus.data.map(function (item) {
                        return item.deviceId;
                    });
                    excuteFlag = true;
                    break;
                }
                case 'scheduleUpload': {
                    $.ajax({
                        url: '/admin/get/schedule',
                        type: 'POST',
                        success: function (res) {
                            if(res.code === 0){
                                var hour = ""
                                var minute = ""
                                console.log("/admin/get/schedule ->res = "+res)
                                if(res.data === "" || res.data === null || res.data === undefined){
                                    hour = null
                                    minute = null
                                }else{
                                    var time = res.data.split(":")
                                    hour = time[0]
                                    minute = time[1]
                                }

                                layer.open({
                                    type: 1,
                                    area: '350px',
                                    resize: false,
                                    shadeClose: true,
                                    title: '设置每日上传脚本执行的定时时间',
                                    content: `
                            <div class="layui-form layui-form-pane" style="padding: 20px;">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">小时</label>
                                    <div class="layui-input-block">
                                        <input type="number" name="hours" value="`+ hour +`" placeholder="请输入小时" class="layui-input" min="0" max="23">
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">分钟</label>
                                    <div class="layui-input-block">
                                        <input type="number" name="minutes" value="`+ minute +`" placeholder="请输入分钟" class="layui-input" min="0" max="59">
                                    </div>
                                </div>
                                <div class="layui-form-item" style="text-align: center;margin-top: 50px">
                                    <button class="layui-btn layui-btn-normal" id="submitBtn">提交</button>
                                    <button class="layui-btn layui-btn-primary" id="cancel" style="margin-left: 70px;">取消</button>
                                </div>

                                </div>
                            </div>
                        `
                                })

                                // 提交按钮点击事件处理
                                document.getElementById('submitBtn').addEventListener('click', function () {
                                    var hours = document.querySelector('input[name="hours"]').value;
                                    var minutes = document.querySelector('input[name="minutes"]').value;
                                    if (hours < 0 || hours > 23) {
                                        layer.msg('小时必须在0到23之间');
                                        return;
                                    }
                                    if (minutes < 0 || minutes > 59) {
                                        layer.msg('分钟必须在0到59之间');
                                        return;
                                    }
                                    if (minutes === null || minutes === "") {
                                        minutes = "0";
                                    }
                                    // 可以在这里处理提交的数据，例如发送到服务器或进行其他操作
                                    console.log("小时: " + hours + ", 分钟: " + minutes);

                                    $.ajax({
                                        url: '/admin/schedule/upload',
                                        method: 'POST',
                                        data: {
                                            hours: hours,
                                            minutes: minutes
                                        },
                                        success: function (res) {
                                            layer.confirm(res.msg, {
                                                btn:['关闭']
                                            },function() {
                                                layer.closeAll(); // 关闭所有弹出层
                                            });

                                        },
                                        error: function (res) {
                                            layer.confirm(res.msg, {
                                                btn:['关闭']
                                            },function() {
                                                layer.closeAll(); // 关闭所有弹出层
                                            });

                                        }
                                    });

                                });

                                // 提交按钮点击事件处理
                                document.getElementById('cancel').addEventListener('click', function () {
                                    layer.closeAll(); // 关闭弹窗
                                });
                            }else{
                                layer.confirm('获取失败！', {btn:['关闭'],function() {
                                        layer.closeAll(); // 关闭所有弹出层
                                    }});
                            }
                        },
                        error: function (res) {
                            console.log(res)
                            layer.confirm('获取失败！', {btn:['关闭'],function() {
                                    layer.closeAll(); // 关闭所有弹出层
                                }});
                        }
                    })


                    break;
                }

            }
            // 如果是执行脚本操作
            if (excuteFlag === true) {
                layer.open({
                    type: 1,
                    title: '选择操作',
                    area: ['600px', '400px'],
                    content: `
                            <div style="padding: 20px;">
                                <table id="selectTable" lay-filter="selectTable"></table>
                            </div>
                        `,
                    success: function (layero, index) {
                        table.render({
                            elem: '#selectTable',
                            data: [
                                {typology: 'excuJs', optionName: '上传视频', code: "request"}
                                // {typology: 'cmd', optionName: '选项二'},
                                // {typology: 'cmd', optionName: '选项三'}
                            ],
                            cols: [[
                                {type: 'radio', fixed: 'left'},
                                {field: 'typology', title: '操作类型', hide: true},
                                {field: 'optionName', title: '名称', width: 200}
                            ]],
                            page: false
                        });
                    },
                    btn: ['提交', '取消'],
                    yes: function (index, layero) {
                        var checkStatus = table.checkStatus('selectTable');
                        var selectedOption = checkStatus.data[0];
                        if (selectedOption) {
                            var result = {
                                deviceIds: deviceIds,
                                cmd: selectedOption.typology,
                                name: selectedOption.code
                            };
                            // 提交结果到接口
                            $.ajax({
                                type: 'POST',
                                url: '/admin/cmd',
                                contentType: 'application/json',
                                data: JSON.stringify(result),
                                success: function (res) {
                                    if (res.code === 0) {
                                        layer.confirm(res.msg, {btn:['关闭']});
                                    } else {
                                        if (res.code === -1) {
                                            layer.confirm(res.msg, {btn:['关闭']});
                                        } else {
                                            layer.confirm('操作失败', {btn:['关闭']});
                                        }
                                    }
                                },
                                error: function (xhr, status, error) {
                                    console.error(xhr, status, error);
                                    layer.confirm('操作失败', {btn:['关闭']});
                                }
                            });

                            console.log(result); // 输出整合后的数据格式
                            layer.close(index); // 关闭弹窗
                        } else {
                            layer.msg('请选择一个操作选项', {icon: 2});
                        }
                    }
                });
            }


        });
    });
</script>
</body>
</html>